package faceattendsystem.servlet;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import faceattendsystem.entity.Employee;
import faceattendsystem.service.IEmployeeService;
import faceattendsystem.serviceImpl.EmployeeServiceImpl;


public class LoginServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		IEmployeeService employeeService = new EmployeeServiceImpl();
		String id = req.getParameter("id");
		String pw = req.getParameter("pw");

		String s = "",f="0";
		Employee employee = employeeService.isEmployee(id);
		if (employee == null) {
			s = "工号不存在!";
		} else {
			try {
				if (!checkPw(pw, employee.getPassword())) {
					s = "密码不匹配!";
				} else {
					f = "1";
					s = "登录成功!";
					req.getSession().setAttribute("employee", employee);
				}
			} catch (NoSuchAlgorithmException e) {
				s = "换个密码试试!";
				//System.out.println("密码检查错误！");
				//e.printStackTrace();
			}
		}
		s = "{\"flag\":\"" + f + "\",\"msg\":\"" + s + "\"}";
		resp.getWriter().print(s);
	}

	/**
	 * 利用MD5进行加密
	 * 
	 * @param str 待加密的字符串
	 * @return 加密后的字符串
	 * @throws NoSuchAlgorithmException 没有这种产生消息摘要的算法
	 */
	private String EncoderByMd5(String str) throws NoSuchAlgorithmException {
		MessageDigest md = MessageDigest.getInstance("MD5");
		md.update(str.getBytes());
		byte b[] = md.digest();
		StringBuffer buf = new StringBuffer("");
		for (int offset = 0; offset < b.length; offset++) {
			int i = b[offset];
			if (i < 0)
				i += 256;
			if (i < 16)
				buf.append("0");
			buf.append(Integer.toHexString(i));
		}
		return buf.toString();
	}

	/**
	 * 判断用户密码是否正确
	 * 
	 * @param newpw 用户输入的密码
	 * @param oldpw 数据库中存储的密码－－用户密码的摘要
	 * @throws NoSuchAlgorithmException
	 */
	public boolean checkPw(String newpw, String oldpw) throws NoSuchAlgorithmException {
//		System.out.println(newpw);
//		System.out.println(oldpw);
//		System.out.println(EncoderByMd5(newpw));
		if (EncoderByMd5(newpw).equals(oldpw))
			return true;
		else
			return false;
	}
}
